/* SuccessFactors URL Shortener */

(function( $ ){

    var methods = {

        init: function( options ) {

            var serviceUrlPrefix = '/s/?';
            var $this = $(this);
            var defaults = {
                "longurl": window.location.href
                ,"shorturl": ""
                ,"callback": ""
                ,"event": {}
                ,"attribute": "data-url"
                ,"track": ""
            };

            var getNewShorturl = true;
            var $window = $(window);
            var settings = $.extend(defaults, options);
            var urlArray = [];
            var alreadyShortened = [];

            if( typeof $window.data('sfshorturl') != 'undefined' && $window.data('sfshorturl').length > 0) {
                urlArray = $window.data('sfshorturl');
            }else{
                $window.data('sfshorturl', [{fired:true}] );
            }

            settings.longurl = $this.data("longurl") ? $this.data("longurl") : settings.longurl;

            // Test to see if this url has already been shortened on this page request
            if(urlArray.length > 0) {

                alreadyShortened = $.grep( urlArray , function(e){

                    if(alreadyShortened.length > 0 || settings.longurl == e.longurl) {
                        return e;
                    }

                });

                if(alreadyShortened.length > 0) {
                    settings.shorturl = alreadyShortened[0].shorturl;
                }
                if( alreadyShortened.length > 0 || ($this.data("url") && $this.data("url").length > 0)) {
                    getNewShorturl = false;
                }

            }

            var callbacks = $.Callbacks( "once" );

            if( settings.callback.length > 0 ){
                callbacks.add( settings.callback );
            }

            return this.each(function(){

                var elementData = {
                    "longurl":settings.longurl
                    ,"shorturl":settings.shorturl
                    ,"event": {
                        "type": settings.event.type
                        ,"target": settings.event.currentTarget
                    }
                    ,"track": settings.track
                    ,"success":true
                }

                var longurl = settings.longurl;

                if(typeof settings.track == 'object' ) {

                    longurl += longurl.indexOf('?') > -1 ? '&' : '?';
                    longurl += 't=' + JSON.stringify(settings.track);

                }

                if ( getNewShorturl ) {

                    $.ajax({
                        url: serviceUrlPrefix + 'longurl=' + encodeURIComponent(longurl)
                        ,cache: false
                        ,type: 'POST'
                        ,success: function(returnData) {

                            elementData.shorturl = returnData.url;
                            $this.data(elementData).attr(settings.attribute,elementData.shorturl);

                            urlArray.push({longurl:settings.longurl,shorturl:returnData.url});

                            $window.data('sfshorturl', urlArray );

                            callbacks.fireWith( window, [ $this.data() ] );

                        }
                        ,error: function(returnData){
                            $this.data("success",false);
                        }
                    });

                } else {

                    elementData.shorturl = settings.shorturl;
                    $this.data(elementData).attr(settings.attribute,elementData.shorturl);

                    callbacks.fireWith( window, [ $this.data() ] );

                }

            });

        }

    };

    $.fn.sfshorturl = function( method ) {

        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.sfshorturl' );
        }

    };

})( jQuery );